import { JSEncrypt } from 'jsencrypt'
import { rsaEncrypt } from '@/utils/index.js'
export default {
  data() {
    return {
      loading: false,
      pwdType: 'password',
      loginForm: {
        userName: 'admin',
        password: 'admin',
        code: ''
      },
      loginRules: {
        userName: [{ required: true, message: '请输入用户名账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
        // code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      }
    }
  },
  created() {},
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          // window.location.href = 'main.html' // 跳过登录
          this.publicKey()
        } else {
          this.$message.warning('输入用户名、密码、验证码即可登陆')
        }
      })
    },
    async publicKey() {
      // 获取加密公钥
      try {
        const res = await this.$api.login.publicKey()
        if (res) {
          this.$wsCache.set('publicKey', res)
          const encrypt = new JSEncrypt()
          encrypt.setPublicKey(res)
          const encrypted = encrypt.encrypt(this.loginForm.password)
          this.$set(this.loginForm, 'password', encrypted)
          this.login()
        }
      } catch (error) {
        this.loading = false
      }
    },
    async login() {
      //  加密后登录
      try {
        const res = await this.$api.login.login(this.loginForm)
        this.loading = false
        if (res.status) {
          this.$wsCache.set('userInfo', res)
          window.location.href = 'main.html'
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        this.loading = false
      }
    }
  }
}
